package com.example.demo.Util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by xiebang
 * Description
 * 通过 Runtime 类得到 runtime 实例 执行exec 方法
 * 2.获取标注输出，并写入到指定文件中
 * 3.获取标准错误，并写入到指定文件中
 * 4.等待子进程结束，拿到子进程的状态码
 * User:小谢
 * Date:2022-09-19
 * Time:11:45
 */
public class CommandUtil {
    public static int run(String cmd,String stdoutFile,String stderrFile)  {
//        通过 Runtime 类得到 runtime 实例 执行exec 方法
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        try {
            process = runtime.exec(cmd);
            if (stdoutFile != null){
                //        获取标注输出，并写入到指定文件中
                InputStream stdoutFrom = process.getInputStream();
                FileOutputStream stdoutTo = new FileOutputStream(stdoutFile);
                while (true){
                    int ch = stdoutFrom.read();
                    if (ch == -1){
                        break;
                    }
                    stdoutTo.write(ch);
                }
                stdoutFrom.close();
                stdoutTo.close();
            }

            if (stderrFile != null){
                //        获取标准错误，并写入到指定文件中
                InputStream stderrFrom = process.getErrorStream();
                FileOutputStream stderrTo = new FileOutputStream(stderrFile);
                while (true){
                    int ch = stderrFrom.read();
                    if (ch == -1){
                        break;
                    }
                    stderrTo.write(ch);
                }
                stderrFrom.close();
                stderrTo.close();
            }

            int exitCode = process.waitFor();
            return exitCode;

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public static void main(String[] args) {
        CommandUtil.run("javac","stdout.txt","stderr.txt");
    }

}
